const { Transform } = require("stream");
const fs = require("fs");
const path = require("path");
const moment = require("moment");
const _ = require("lodash");
const utils = require('../../utils');

module.exports = function(file, { type = 0, inFormat } = {}) { // type： 0: js 1: json 2:inline-js 3:inline-json
  const stream = new Transform({ objectMode: true });
  inFormat = utils.parseFunction(inFormat);
  const fd = fs.openSync(file, 'w');
  fs.writeSync(fd, 'module.exports = [\n');

  stream._transform = function (chunk, encoding, callback) {
    utils.debug('jsonWriter [chunk]:', chunk);
    stream.push(chunk);
    const obj = inFormat ? inFormat(chunk, { _, moment, utils }) : chunk;
    fs.write(fd, utils.stringify(obj, type, 2, ' ') + ',\n', callback);
  };
  
  stream.on('finish', function () {
    fs.writeSync(fd, ']');
    fs.close(fd);
    utils.debug('jsonWriter [finish]');
  });

  return stream;
};